#include<pthread.h>
#include"Util.hpp"
#include"Config.hpp"
#include <unordered_map>
namespace cloud
{
    typedef struct BackupInfo
    {
        bool pack_flag; //标识文件是否被压缩
        size_t fsize;
        time_t mtime;
        time_t atime;
        string real_path;
        string pack_path;
        string url; // 下载路径
        void NewBackupInfo(const string &realpath)
        {
            Config *config = Config::GetInstance();
            string packdir = config->GetPackDir();
            string packsuffix = config->GetPackFileSuffix();
            string download_prefix = config->GetDownloadPrefix();
            FileUtil fu(realpath);
            this->pack_flag = false;
            this->fsize = fu.FileSize();
            this->mtime = fu.LastMTime();
            this->atime = fu.LastATime();
            this->real_path = realpath;
            this->pack_path = packdir + fu.FileName() + packsuffix;
            this->url = download_prefix + fu.FileName();
        }
    };

    class DataManager
    {
    private:
        string _backup_file;
        pthread_rwlock_t _rwlock;
        std::unordered_map<string, BackupInfo> _table;

    public:
        DataManager()
        {
            _backup_file = Config::GetInstance()->GetBackupFile();
            pthread_rwlock_init(&_rwlock, nullptr);
            InitLoad();
        }
        ~DataManager()
        {
            pthread_rwlock_destroy(&_rwlock);
        }
        bool Insert(const BackupInfo &info)
        {
            pthread_rwlock_wrlock(&_rwlock);
            _table[info.url] = info;
            pthread_rwlock_unlock(&_rwlock);
            Storage();      //每次插入新数据都要进行一次存储
            return true;
        }
        bool Update(const BackupInfo &info)
        {
            pthread_rwlock_wrlock(&_rwlock);
            _table[info.url] = info;
            pthread_rwlock_unlock(&_rwlock);
            Storage();  //每次插入新数据都要进行一次存储
            return true;
        }
        bool GetOneByURL(const string &url, BackupInfo *info)
        {
            pthread_rwlock_wrlock(&_rwlock);
            auto it = _table.find(url);
            if (it == _table.end())
            {
                pthread_rwlock_unlock(&_rwlock);
                return false;
            }
            pthread_rwlock_unlock(&_rwlock);
             *info = it->second;
            return true;
        }
        bool GetOneByRealPath(const string &realpath, BackupInfo *info)
        {
            pthread_rwlock_wrlock(&_rwlock);
            auto it = _table.begin();
            for (; it != _table.end(); ++it)
            {
                if (it->second.real_path == realpath)
                {
                    *info = it->second;
                    pthread_rwlock_unlock(&_rwlock);
                    return true;
                }
            }
            pthread_rwlock_unlock(&_rwlock);
            return false;
        }
        bool GetAll(vector<BackupInfo> *arry)
        {
            pthread_rwlock_wrlock(&_rwlock);
            auto it = _table.begin();
            for (; it != _table.end(); ++it)
            {
                arry->push_back(it->second);
            }
            pthread_rwlock_unlock(&_rwlock);
            return true;
        }
        bool Storage()  //每次有信息改变则需要将所有文件持久化存储一次
        {
            //1.获取所有数据
            vector<BackupInfo>arry;
            this->GetAll(&arry);
            //2.添加到Json::Value
            Json::Value root;
            for(int i=0;i<arry.size();i++)
            {
                Json::Value item;
                item["pack_flag"]=arry[i].pack_flag;
                item["fsize"]=(Json::Int64)arry[i].fsize;
                item["atime"]=(Json::Int64)arry[i].atime;
                item["mtime"]=(Json::Int64)arry[i].mtime;
                item["real_path"]=arry[i].real_path;
                item["pack_path"]=arry[i].pack_path;
                item["url"]=arry[i].url;
                root.append(item);
            }
            //对Json::Value序列化
            string body;
            JsonUtil::Serialize(root,&body);
            //4.写文件
            FileUtil fu(_backup_file);  
            fu.SetContent(body);    //将所有文件写入到备份文件夹中
            return true;
        }
        bool InitLoad() //每次开启时自动初始化数据到内存中
        {
            //1.讲数据文件中的数据读取出来
            FileUtil fu(_backup_file);
            if(fu.Exists()==false)
            return true;
            string body;
            fu.GetContent(&body);
            //2.反序列化
            Json::Value root;
            JsonUtil::UnSerialize(body,&root);
            //3.将反序列化得到的Json::Value中的数据加载到内存中
            for(int i=0;i<root.size();i++)
            {
                BackupInfo info;
                info.pack_flag=root[i]["pack_flag"].asBool();
                info.fsize=root[i]["fsize"].asInt64();
                info.atime=root[i]["atime"].asInt();
                info.mtime=root[i]["mtime"].asInt64();
                info.pack_path=root[i]["pack_path"].asString();
                info.real_path=root[i]["real_path"].asString();
                info.url=root[i]["url"].asString();
                Insert(info);
            }
            return true;
        }
    };
};